import { defineStore } from 'pinia'
import { ref } from 'vue'
import { Product, ProductQueryParams, PageResponse, PageView } from '@/types'
import request from '@/utils/request'

export const useProductStore = defineStore('product', () => {
  // 状态
  const products = ref<Product[]>([])
  const currentProduct = ref<Product | null>(null)
  const loading = ref(false)
  const total = ref(0)

  // 获取商品列表
   // 获取商品列表
   const getProducts = async (params: any) => {
    loading.value = true
    try {
      const response = await request.get('/product/list', { params })  
      console.log(response);
      
      const pageData = response.data
      products.value = pageData.records
      total.value = pageData.total
      return {
        list: pageData.records,
        total: pageData.total,
        page: pageData.current,
        pageSize: pageData.size
      }
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }


  const userStr = localStorage.getItem('user')
  const user = userStr ? JSON.parse(userStr) : null


  // 获取商品详情
  const getProductDetail = async (id: number): Promise<Product | null> => {
    try {
      const response = await request.get(`/product/admin/${id}`, {
        params: {
          userName: user?.nickname || ''
        }
      })
      console.log('获取商品详情响应:', response)
      currentProduct.value = response.data
      return response.data
    } catch (error) {
      console.error('获取商品详情失败:', error)
      throw error
    }
  }

  // 创建商品
  const createProduct = async (productData: any) => {
    try {
      const response = await request.post('/product/add', productData)
      console.log('创建商品响应:', response)
      return response
    } catch (error) {
      console.error('创建商品失败:', error)
      throw error
    }
  }

  // 更新商品
  const updateProduct = async (productData: any) => {
    try {
      const response = await request.post('/product/update', productData)
      console.log('更新商品响应:', response)
      return response
    } catch (error) {
      console.error('更新商品失败:', error)
      throw error
    }
  }

  // 删除商品
  const deleteProduct = async (id: number) => {
    try {
      const response = await request.delete(`/product/${id}`)
      console.log('删除商品响应:', response)
      return response
    } catch (error) {
      console.error('删除商品失败:', error)
      throw error
    }
  }

  // 获取我的商品
  const getMyProducts = async (params: { pageNum: number; pageSize: number; userName: string; sortBy?: string }) => {
    loading.value = true
    try {
      const response = await request.get('/product/userlist', { params })
      console.log('我的商品API响应:', response)
      
      if (response && response.data) {
        const pageData = response.data
        let products = pageData.data || []
        
        // 如果后端不支持排序，在前端进行排序
        if (params.sortBy) {
          products = sortProducts(products, params.sortBy)
        } else {
          // 默认按发布时间倒序排列
          products = sortProducts(products, 'createTime-desc')
        }
        
        products.value = products
        total.value = pageData.allRow || 0
        return {
          list: products,
          total: pageData.allRow || 0,
          page: pageData.pageNum || 1,
          pageSize: pageData.pageSize || 10
        }
      } else {
        throw new Error('响应数据格式错误')
      }
    } catch (error) {
      console.error('获取我的商品失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取我的收藏/浏览历史
  const getUserCollect = async (params: { pageNum: number; pageSize: number; userName: string; type: number; categoryId?: string; sortBy?: string }) => {
    loading.value = true
    try {
      const response = await request.get('/product/collect', { params })
      console.log('收藏/浏览API响应:', response)
      
      if (response && response.data) {
        const pageData = response.data
        let products = pageData.data || []
        
        // 如果后端不支持分类筛选，在前端进行筛选
        if (params.categoryId && params.categoryId !== '') {
          products = products.filter((product: any) => product.categoryId === Number(params.categoryId))
        }
        
        // 如果后端不支持排序，在前端进行排序
        if (params.sortBy) {
          products = sortProducts(products, params.sortBy)
        }
        
        return {
          list: products,
          total: products.length, // 使用筛选后的数量
          page: pageData.pageNum || 1,
          pageSize: pageData.pageSize || 10
        }
      } else {
        throw new Error('响应数据格式错误')
      }
    } catch (error) {
      console.error('获取收藏/浏览失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 排序商品
  const sortProducts = (products: any[], sortBy: string) => {
    const [field, order] = sortBy.split('-')
    
    return products.sort((a, b) => {
      let aValue, bValue
      
      switch (field) {
        case 'createTime':
          aValue = new Date(a.createTime).getTime()
          bValue = new Date(b.createTime).getTime()
          break
        case 'price':
          aValue = a.price || 0
          bValue = b.price || 0
          break
        default:
          aValue = new Date(a.createTime).getTime()
          bValue = new Date(b.createTime).getTime()
      }
      
      if (order === 'asc') {
        return aValue - bValue
      } else {
        return bValue - aValue
      }
    })
  }

  // 获取我的订单
  const getUserOrders = async (params: { pageNum: number; pageSize: number; userName: string; sortBy?: string }) => {
    loading.value = true
    try {
      const response = await request.get('/orders/userlist', { params })
      console.log('我的订单API响应:', response)
      
      if (response && response.data) {
        const pageData = response.data
        let orders = pageData.data || []
        
        // 如果后端不支持排序，在前端进行排序
        if (params.sortBy) {
          orders = sortOrders(orders, params.sortBy)
        }
        
        return {
          list: orders,
          total: pageData.allRow || 0,
          page: pageData.pageNum || 1,
          pageSize: pageData.pageSize || 10
        }
      } else {
        throw new Error('响应数据格式错误')
      }
    } catch (error) {
      console.error('获取我的订单失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 排序订单
  const sortOrders = (orders: any[], sortBy: string) => {
    const [field, order] = sortBy.split('-')
    
    return orders.sort((a, b) => {
      let aValue, bValue
      
      switch (field) {
        case 'createTime':
          aValue = new Date(a.createTime).getTime()
          bValue = new Date(b.createTime).getTime()
          break
        case 'tradeTime':
          aValue = a.tradeTime ? new Date(a.tradeTime).getTime() : 0
          bValue = b.tradeTime ? new Date(b.tradeTime).getTime() : 0
          break
        case 'price':
          aValue = a.buyPrice || 0
          bValue = b.buyPrice || 0
          break
        default:
          aValue = new Date(a.createTime).getTime()
          bValue = new Date(b.createTime).getTime()
      }
      
      if (order === 'asc') {
        return aValue - bValue
      } else {
        return bValue - aValue
      }
    })
  }

  // 获取最新商品
  const getLatestProducts = async (limit: number = 4) => {
    try {
      const response = await request.get('/product/list', {
        params: {
          pageNum: 1,
          pageSize: limit,
          sortBy: 'createTime',
          sortOrder: 'desc'
        }
      })
      console.log('最新商品API响应:', response)
      
      if (response && response.data && response.data.records) {
        // 确保按创建时间排序，取最新的4个商品
        const sortedProducts = response.data.records.sort((a: any, b: any) => {
          const timeA = new Date(a.createTime).getTime()
          const timeB = new Date(b.createTime).getTime()
          return timeB - timeA // 降序排列，最新的在前
        })
        
        return sortedProducts.slice(0, limit)
      } else {
        return []
      }
    } catch (error) {
      console.error('获取最新商品失败:', error)
      return []
    }
  }

  // 获取商品总数
  const getProductCount = async () => {
    try {
      const response = await request.get('/product/list', {
        params: {
          pageNum: 1,
          pageSize: 1
        }
      })
      console.log('商品总数API响应:', response)
      
      if (response && response.data && response.data.total !== undefined) {
        return response.data.total
      } else {
        return 0
      }
    } catch (error) {
      console.error('获取商品总数失败:', error)
      return 0
    }
  }

  // 收藏商品
  const favoriteProduct = async (productId: number) => {
    try {
      const response = await request.post('/user/actions', {
        productId,
        actionType: 1
      })
      return response
    } catch (error) {
      throw error
    }
  }

  // 取消收藏
  const unfavoriteProduct = async (productId: number) => {
    try {
      const response = await request.delete(`/user/actions/${productId}/1`)
      return response
    } catch (error) {
      throw error
    }
  }

  // 记录浏览
  const recordView = async (productId: number) => {
    try {
      const response = await request.post('/user/actions', {
        productId,
        actionType: 2
      })
      return response
    } catch (error) {
      throw error
    }
  }

  // 完成订单
  const completeOrder = async (orderData: { detail: string; code: string }) => {
    try {
      const response = await request.post('/orders/complete', null, {
        params: orderData
      })
      console.log('完成订单响应:', response)
      return response
    } catch (error) {
      console.error('完成订单失败:', error)
      throw error
    }
  }

  // 创建订单
  const createOrder = async (orderData: { productId: number; userName: string }) => {
    try {
      const response = await request.post('/orders/add', null, {
        params: orderData
      })
      console.log('创建订单响应:', response)
      return response
    } catch (error) {
      console.error('创建订单失败:', error)
      throw error
    }
  }

  return {
    products,
    currentProduct,
    loading,
    total,
    getProducts,
    getProductDetail,
    createProduct,
    updateProduct,
    deleteProduct,
    getMyProducts,
    getUserCollect,
    getUserOrders,
    getLatestProducts,
    getProductCount,
    favoriteProduct,
    unfavoriteProduct,
    recordView,
    completeOrder,
    createOrder
  }
}) 